package com.ruoyi.client.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.client.domain.vo.TagsTreeVo;
import com.ruoyi.client.domain.entity.BlogTags;
import com.ruoyi.client.domain.entity.BlogTagsCategory;
import com.ruoyi.client.mapper.BlogTagsCategoryMapper;
import com.ruoyi.client.mapper.BlogTagsMapper;
import com.ruoyi.client.service.IBlogTagsCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 标签分类表 服务实现类
 * </p>
 *
 * @author fz
 * @since 2025-02-27
 */
@Service
public class BlogTagsCategoryServiceImpl extends ServiceImpl<BlogTagsCategoryMapper, BlogTagsCategory> implements IBlogTagsCategoryService {
    @Autowired
    BlogTagsMapper tagsMapper;

    @Override
    public TableDataInfo<BlogTagsCategory> selectBlogTagCategoryList(PageQuery query) {
        Page<BlogTagsCategory> page = this.page(query.build(), buildWrapper(query.getParams()));
        return TableDataInfo.build(page);
    }

    /**
     * 通过tag分类构建属性结构
     * @return
     */
    @Override
    public List<TagsTreeVo> tree() {
        List<BlogTagsCategory> blogCategoryList = list(Wrappers.<BlogTagsCategory>lambdaQuery().eq(BlogTagsCategory::getStatus, 1));
        List<Long> categoryIds = blogCategoryList.stream().map(v -> v.getId()).collect(Collectors.toList());

        //获取categoryId在categoryIds中的状态为1（正常）的tags
        List<BlogTags> tagsList = tagsMapper.selectList(Wrappers.<BlogTags>lambdaQuery()
            .eq(BlogTags::getStatus, 1)
            .in(BlogTags::getCategoryId, categoryIds)
        );
        //构建tagsTreeVo
        List<TagsTreeVo> result = buildTree(blogCategoryList,tagsList);
        return result;
    }
    private List<TagsTreeVo> buildTree(List<BlogTagsCategory> blogTagsCategoryList,List<BlogTags> tagsList){
        Map<Long, List<BlogTags>> map = tagsList.stream().collect(Collectors.groupingBy(BlogTags::getCategoryId));
        ArrayList<TagsTreeVo> list = new ArrayList<>();
        for (BlogTagsCategory category : blogTagsCategoryList) {
            TagsTreeVo treeVo = new TagsTreeVo();
            treeVo.setId(category.getId());
            treeVo.setName(category.getName());
            treeVo.setTagsList(map.get(category.getId()));
            list.add(treeVo);
        }
        return list;
    }
    /**
     * 添加标签分类
     * @param tagsCategory
     * @return
     */
    @Override
    public boolean addBlogTagCategory(BlogTagsCategory tagsCategory) {
        checkTag(tagsCategory);
        return save(tagsCategory);
    }

    /**
     * 更新标签分类
     * @param blogTagsCategory
     * @return
     */
    @Override
    public boolean updateTagCategory(BlogTagsCategory blogTagsCategory) {
        checkTag(blogTagsCategory);
        return updateById(blogTagsCategory);
    }

    /**
     * 删除标签分类
     * @param ids
     * @return
     */
    @Override
    public boolean deleteTagCategory(Long[] ids) {
        // 检查标签分类下是否关联标签
        Arrays.stream(ids).forEach(id ->{
            BlogTagsCategory blogTagsCategory = getById(id);
            if (tagsMapper.exists(Wrappers.<BlogTags>lambdaQuery().eq(BlogTags::getTagType,blogTagsCategory.getTagType()))) {
                throw new ServiceException(String.format("%1$s已分配，不能删除",blogTagsCategory.getName()));
            }
        });
        return removeBatchByIds(Arrays.asList(ids));
    }

    /**
     * 检查是否存在相同名字或者类型的标签分类
     * @param tagsCategory
     */
    private void checkTag(BlogTagsCategory tagsCategory){
        BlogTagsCategory one = getOne(Wrappers.<BlogTagsCategory>lambdaQuery()
            .eq(BlogTagsCategory::getName, tagsCategory.getName())
            .or()
            .eq(BlogTagsCategory::getTagType, tagsCategory.getTagType())
        );
        if (tagsCategory.getId() == null){
            if (one != null) {
                throw new ServiceException("该标签类型已存在");
            }
        }
        else {
            if (one != null && one.getId() != one.getId()){
                throw new ServiceException("该标签类型已存在");
            }
        }
    }

    private Wrapper<BlogTagsCategory> buildWrapper(Map<String, Object> params) {
        QueryWrapper<BlogTagsCategory> wrapper = new QueryWrapper<>();
        if (CollectionUtils.isEmpty(params)) return wrapper;
        String beginTime = (String) params.get("beginTime");
        String endTime = (String) params.get("endTime");
        if (StringUtils.isNotEmpty(beginTime) && StringUtils.isNotEmpty(endTime)){
            wrapper.between("create_time",beginTime,endTime);
            params.remove("beginTime");
            params.remove("endTime");
        }
        Set<Map.Entry<String, Object>> set = params.entrySet();
        for (Map.Entry<String, Object> entry : set) {
            String field = entry.getKey();
            Object value = entry.getValue();

            if (value != null) {
                // 添加等值条件
                wrapper.like(field,value);
            }
        }
        return wrapper;
    }
}
